<?php

namespace IDock\Insurance\HBIC\Response;

use IDock\Printer\PolicyPaymentPrinter;
use IDock\Http\Response;

class InsurancePayUrlResponse extends AllHBICResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            $body = str_replace('&','&amp;',$body);
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $errorCode = $body['HEAD']['ERROR_CODE'] ?? '';
            $message = $body['HEAD']['ERROR_MESSAGE'] ?? '';
            $this->setBody($body);
            if ($errorCode != '0000') {
                $this->setError(  ($errorCode ?: '') .":".$message);
                return  $this;
            }
        }
        return $this;
    }
    public function printerInit(): Response
    {
        $policyPaymentPrinter = new PolicyPaymentPrinter();

        $data = $this->getBody() ?? [];
        $url = $data['body']['baseInfo']['payUrl'] ?? '';
        $msgInfo = $data['body']['baseInfo']['msgInfo'] ?? '';
        if(empty($url)){
            $error = '获取支付链接失败';
            if(!empty($msgInfo)){
                $error = $msgInfo;
            }
            $this->setError($error);
            $this->printer = $policyPaymentPrinter;
            return $this;
        }
        $this->setCode('200');
        $policyPaymentPrinter->payUrl = $url;

        $this->printer = $policyPaymentPrinter;
        return $this;
    }
}
